package de.gameduell.framework.fakeserver {

	/**
	 * @author dkum
	 */
	public class Storyboard {

		public static const WAIT:String = "wait";
		public static const CHOICE:String = "choice";
		public static const AUTOMATE:String = "automate";
		public static const AUTOMATE_OFF:String = "automate_off";
		private var storyboardXML:XML;
		private var _messages:Array = new Array();

		public function Storyboard(aStoryboardXml:XML):void {
			storyboardXML = aStoryboardXml;
			_messages = parseMessages(storyboardXML.children());
		}
		
		private function parseMessages(actions:XMLList):Array{
			var parsedMessages:Array = new Array;
			
			for(var i:* in actions) {
				var actionNode:XML = XML(actions[i]);
				if(actionNode.name() == WAIT) {
					var awaitedActions:XMLList = actionNode.children();
					var waitMessages:Array = new Array();
					for(var j in awaitedActions) {
						var awaitedActionNode:XML = XML(awaitedActions[j]);
						waitMessages.push([awaitedActionNode.name(),awaitedActionNode.toString().split("\t")]);
					}
					var block:Boolean = (actionNode.attribute("block").toString() != "false");
					parsedMessages.push([actionNode.name(),waitMessages,block]);
				} else if (actionNode.name() == CHOICE){
					var options:XMLList = actionNode.children();
					var choiceContent:Array = new Array();
					for(var h in options) {
						var option:XML = XML(options[h]);
						var optionMessage:String = option.attribute("message").toString();
						var optionParameters:String = option.attribute("parameters").toString();
						choiceContent.push([optionMessage,parseMessages(option.children()),optionParameters]);
					}
					parsedMessages.push([actionNode.name(),choiceContent]);
				} else {
					var content:Array = actionNode.toString().split("\t");
					if (actionNode.attribute("variables").toString() == "true") {
						var variables:Array = new Array();
						for (var k in content) {
							if (content[k].charAt(0) == "§") {
								var variableData:Array = new Array();
								variableData.push(k);
								variableData.push(String(content[k]).substr(1, content[k].length - 1));
								variables.push(variableData);
							}
						}
						parsedMessages.push([actionNode.name(),content,variables]);
					} else {
						parsedMessages.push([actionNode.name(),content]);
					}
				}
			}
			
			return parsedMessages;
		}

		public function get messages():Array {
			return _messages;
		}
	}
}
